<template>
  <el-form v-model="data"
           label-width="100px">
  <el-row :gutter="20">
    <el-col :span="12" v-for="(item, index) in data" :key="index">

      <dynamic-form-item :item="item"
                         v-model="item.defaultValue"
      ></dynamic-form-item>

    </el-col>
  </el-row>
  </el-form>
</template>
<script>
import dynamicFormItem from './dynamicFormItem'
export default {
  components: {
    dynamicFormItem
  },
  props: {
    data: {
      type: Array,
      required: true
    }
  },
  computed: {
    checkRules () {
      const { item: { rules } } = this
      const { item: { required } } = this
      const { item: { formName } } = this
      console.log(rules)
      if (rules === undefined || rules === null) return undefined

      const R = []

      rules.forEach(rule => {
        if (required) {
          var obj = { required: required, message: formName + '不能为空' }
          R.push(obj)
        }
        if (rule.checkRule) {
          const validator = (rule, value, callback) => {
            // eslint-disable-next-line
              // request('/api/validate', 'POST', {
            //   key: rule2.field,
            //   value,
            //   sql: rule.sql.replace(/{key}/gi, rule2.field)
            // })
            //   .then(res => {
            //     // eslint-disable-next-line
            //     callback(!res || undefined);
            //   })
            //   .catch(err => {
            //     this.$message.error(err.message)
            //     // eslint-disable-next-line
            //     callback(false);
            //   })

            var reg = rule.checkRule
            callback(reg.test(value))
          }

          R.push({ validator, message: rule.message, trigger: 'blur' })
        }
        // else {
        //   R.push(rule)
        // }
      })

      return R
    }
  },
  mounted () {
    this.setDefaultValue()
  },
  methods: {
    handleInput (val, key) {
      // 这里element-ui没有上报event，直接就是value了
      console.log(...this.value)
      console.log(val)
      console.log(val)
      this.$emit('input', { ...this.value, [this.value[key].defaultValue]: val })
    },
    setDefaultValue () {
      const formData = { ...this.value }
      // 设置默认值
      // this.data.forEach(item => {
      //   const { key, value } = item
      //   if (formData[key] === undefined || formData[key] === null) {
      //     formData[key] = value
      //   }
      // })
      this.$emit('input', { ...formData })
    }
  }
}
</script>
